import {
  AsyncStorage,
} from 'react-native';

export default class CollectionDao {
  getData() {
    return new Promise((resolve, reject) => {
      AsyncStorage.getItem('collect', (error, result) => {
        if (error) {
          reject(error);
          return;
        }
        if (!result) {
          resolve('');
        } else {
          try {
            resolve(JSON.parse(result));
          } catch (e) {
            reject(error);
          }

        }
      });
    });
  }
  saveData(objectData) {
    this.getData().then(res => {
      let arr = res ? res: [];
      arr.push(objectData);
      AsyncStorage.setItem('collect', JSON.stringify(arr), (error, result) => {

      });
    })
  }

  removeData(obj) {
    this.getData().then(res => {
      if(res) {
        let arr = [];
        for(let i=0; i< res.length; i++) {
          if(res[i].id === obj.id) {

          }else {
            arr.push(res[i])
          }
        }
        AsyncStorage.setItem('collect', JSON.stringify(arr), (error, result) => {
  
        });
      }else {
        console.log('数据错误')
      }
    })
  }

  /**
   * 从本地数据库中检测是否被收藏
   * @param {*} obj 
   */
  checkData(obj) {
    return new Promise((resolve, reject) => {
      this.getData().then(res => {
        if(res) {
          for(let i=0; i<obj.length; i++) {
            for(let j =0; j<res.length; j++) {
              if(obj[i].id === res[j].id) {
                obj[i].show =true
              }
            }
          }
          resolve(obj);
        }else {
          resolve(obj);
        }
      })
    })
  }
}